import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}
// 口诀: return右侧的值返回到本次函数调用处

const state = getDefaultState()

const mutations = {
  // 重置state
  RESET_STATE: (state) => {
    // Object.assign() 合并对象
    // 作用: 参数2后面所有对象的key和value, 合并到参数1的对象身上(遇到 重名的key后者覆盖前者)
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

// 知识点: actions方法用dispatch调用后在dispatch原地始终返回的是一个Promise对象
// 如果自己有return 一个Promise对象会覆盖掉它默认返回的
const actions = {
  // user login
  // login(store, userInfo) {}
  // login({ commit }, userInfo) {}
  // 登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
    // login是最上面引入的登录接口方法
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        // 把token值保存在vuex和本地cookie中
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        // 告诉actions调用处, 登录成功了
        resolve()
      }).catch(err => {
        console.log(err)
      })
    })
  },

  // 请求和响应, http状态码 200/400, axios内部做判断
  // 逻辑状态码, http状态码 全都是200(逻辑成功还是失败), 导致promise对象成功, 后续你要根据code做判断

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { name, avatar } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

